import { Button, message, Space } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { getDvaApp, history, Link } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';
import $utils from '@/utils/utils';
import { getJobsList, getJobsNames } from '@/services/jobs';


const BasicConfig: React.FC = () => {

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;
    const actionRef = useRef<ActionType>();
    const formRef = useRef<ProFormInstance>();

    const [initParams, setParams] = useState<any>();
    const [jobsNames, setJobsNames] = useState<any>();
    const [pageSize, setPageSize] = useState<number>(20);

    useEffect(() => {
        const getJobsData = async () => {
            try {
                const msg = await getJobsNames({ name: '' });
                let new_data: API.Select[] = [];
                if (msg.code === 0) {
                    msg.body.map((item: { id: number, name: string }) => {
                        new_data.push({
                            label: item.name,
                            value: item.id,
                        });
                    });
                    setJobsNames(new_data);
                    return;
                }
            } catch (error) {
                message.error(`${error}`);
            }
        };

        getJobsData();
    }, []);

    const l_state: any = history.location.state;
    useEffect(() => {
        if (!initParams) {
            const data = {
                ...l_state,
            };
            setParams(data);
        }
    }, []);

    // 筛选重置时更新表单
    useEffect(() => {
        if (JSON.stringify(initParams) === '{}') {
            formRef && formRef.current?.resetFields();
            actionRef?.current?.reset && actionRef?.current?.reset();
        }
    }, [initParams]);

    const columns: ProColumns<any>[] = [
        {
            title: 'ID',
            dataIndex: 'id',
            search: false,
        },
        {
            title: '岗位名称',
            dataIndex: 'name',
            valueType: 'select',
            fieldProps: {
                placeholder: '请输入内容',
                showSearch: true,
                options: jobsNames
            },
            render: (dom, entity) => {
                const handleJump = () => {
                    const newTab = {
                        name: `查看${entity.name}`,
                        path: '/System/jobs/detail',
                        state: {
                            status: 'detail',
                            data: entity
                        },
                    };
                    // 设置当前tab对象
                    $utils.setNewTab(dispatch, newTab);
                    $utils.addTab(dispatch, newTab)
                    history.push({
                        pathname: '/System/jobs/detail',
                        state: {
                            status: 'detail',
                            data: entity
                        }
                    });
                };
                return (
                    <div key={entity.id} style={{ cursor: 'pointer' }} onClick={() => {
                        handleJump();
                    }}>
                        {dom}
                    </div >
                )
            }
        },
        {
            title: '添加人',
            dataIndex: 'createUserName',
            // sorter: true,
            search: false,
            hideInForm: true,
        },
        {
            title: '添加时间',
            dataIndex: 'createTime',
            search: false,
            hideInForm: true,
        },
        {
            title: '最新修改人',
            dataIndex: 'updateUserName',
            search: false,
            hideInForm: true,
        },
        {
            title: '修改时间',
            dataIndex: 'updateTime',
            search: false,
            hideInForm: true,
        },
        {
            title: '岗位状态',
            dataIndex: 'status',
            valueType: 'select',
            fieldProps: {
                label: '状态',
                placeholder: '全部',
                options: [
                    { label: '启用', value: 1 },
                    { label: '禁用', value: 2 },
                ]
            },
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [
                <Space key={record.id}>
                    <Button type="primary" size="small" onClick={() => {
                        const newTab = {
                            name: `编辑${record.name}`,
                            path: '/System/jobs/detail',
                            state: {
                                status: 'update',
                                data: record
                            }
                        };
                        // 设置当前tab对象
                        $utils.setNewTab(dispatch, newTab);
                        $utils.addTab(dispatch, newTab);

                        history.push({
                            pathname: '/System/jobs/detail',
                            state: {
                                status: 'update',
                                data: record
                            }
                        });
                    }}>编辑</Button>
                </Space>
            ],
        },
    ];

    return (
        <PageContainer>
            {initParams && <ProTable<API.RuleListItem, API.PageParams>
                actionRef={actionRef}
                rowKey="id"
                pagination={{
                    pageSize: pageSize,
                    showSizeChanger: true,
                    size: 'small',
                    onShowSizeChange: (current, pageSize) => {
                        setPageSize(pageSize);
                    }
                }}
                formRef={formRef}
                search={{
                    labelWidth: 120,
                    defaultCollapsed: false,
                    collapseRender: () => false,
                    span: {
                        xs: 24,
                        sm: 24,
                        md: 12,
                        lg: 12,
                        xl: 8,
                        xxl: 8,
                    },
                    optionRender: (searchConfig, formProps, dom) => [
                        dom.reverse()[0],
                        <Button
                            key="resetText"
                            onClick={() => {
                                setParams({});
                            }}
                        >
                            重置
                        </Button>,
                    ],
                }}
                beforeSearchSubmit={(params) => {
                    params.name && (params.id = params.name);
                    return params;
                }}
                form={{
                    initialValues: initParams
                }}
                options={false}
                title={() => [
                    <Button key={'index'} type="primary" onClick={() => {
                        const newTab = {
                            name: `新建岗位`,
                            path: '/System/jobs/detail',
                            state: {
                                status: 'create',
                                data: jobsNames
                            }
                        };
                        // 设置当前tab对象
                        $utils.setNewTab(dispatch, newTab);
                        $utils.addTab(dispatch, newTab);

                        history.push({
                            pathname: '/System/jobs/detail',
                            state: {
                                status: 'create',
                                data: jobsNames
                            }
                        });
                    }}>新建岗位</Button>
                ]}
                request={async (params) => {
                    const msg = await getJobsList(params);
                    if (msg.code === 0) {
                        // 将筛选条件存进 tabs
                        $utils.addTab(dispatch, {
                            name: '岗位管理',
                            path: '/System/jobs',
                            isTopMenu: true,
                            state: params
                        });
                    }
                    return {
                        data: msg.body?.data || [],
                        success: msg.code === 0,
                        total: msg.body?.count,
                    }
                }}
                columns={columns}
            />}
        </PageContainer >
    );
};

export default BasicConfig;
